package com.cuijq.counterv2.reporter;

import com.cuijq.counterv2.entity.RequestInfo;
import com.cuijq.counterv2.service.MetricsStorage;
import com.cuijq.counterv2.utils.Aggregator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Classname ConsoleReporter
 * @Description TODO
 * @Date 2021/5/4 15:05
 * @Created by CuiJQ
 */
public class ConsoleReporter {

  private MetricsStorage metricsStorage;
  private Aggregator aggregator;
  private StatViewer viewer;
  private ScheduledExecutorService executor;

  public ConsoleReporter(MetricsStorage metricsStorage, Aggregator aggregator, StatViewer viewer) {
    this.metricsStorage = metricsStorage;
    this.aggregator = aggregator;
    this.viewer = viewer;
    this.executor = Executors.newSingleThreadScheduledExecutor();
  }

  public ConsoleReporter(MetricsStorage storage) {
  }

  public void startRepeatedReport(long periodInSeconds, long durationInSeconds) {
    executor.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        long durationInMillis = durationInSeconds * 1000;
        long endTimeInMillis = System.currentTimeMillis();
        long startTimeInMillis = endTimeInMillis - durationInMillis;
        Map<String, List<RequestInfo>> requestInfos = metricsStorage
            .getRequestInfos(startTimeInMillis, endTimeInMillis);
        Map<String, List<RequestInfo>> requestStats = aggregator.aggregate(requestInfos, durationInMillis);
        viewer.output(requestStats, startTimeInMillis, endTimeInMillis);
      }
    }, 0L, periodInSeconds, TimeUnit.SECONDS);
  }
}
